<template>
    <div class="bgColorF" :style="{ height: pcHeight }">
        <div class="flex-row mgT10 mgL15">
            <div
                class="mgR20 w360 pd10 overflow-y boxShadow"
                :style="{ height: pcHeight2 }"
            >
                <el-button
                    class="w35 mgR5"
                    text
                    title="新增一级文件夹"
                    @click="folderSubmit(2, 0, 0, '')"
                >
                    <el-icon :size="24">
                        <CirclePlus />
                    </el-icon>
                </el-button>
                <el-input
                    v-model="filterText"
                    placeholder="输入文件夹名称查询"
                    clearable
                    style="width: 87%"
                />
                <div>
                    <el-tree
                        ref="treeRef"
                        node-key="id"
                        class="filter-tree mgT15"
                        :data="folderData"
                        :props="defaultProps"
                        default-expand-all
                        icon="CaretRight"
                        :filter-node-method="filterNode"
                        :empty-text="loadingDataMsg"
                        :highlight-current="treeHighlightCurrent"
                        :expand-on-click-node="false"
                        :draggable="true"
                        @node-click="btnCheckNode"
                        @node-drag-end="handleDragEnd"
                    >
                        <template #default="{ node, data }">
                            <span class="custom-tree-node">
                                <span class="line-clamp2" :title="node.label">
                                    {{ data.label }}
                                </span>
                                <span>
                                    <el-button
                                        class="w15 pd0 mg0"
                                        text
                                        title="新增下级文件夹"
                                        @click="
                                            folderSubmit(2, data.value, 0, '')
                                        "
                                    >
                                        <el-icon :size="20">
                                            <CirclePlus />
                                        </el-icon>
                                    </el-button>

                                    <el-button
                                        class="w15 pd0 mg0"
                                        text
                                        title="修改文件夹名称"
                                        @click="
                                            folderSubmit(
                                                3,
                                                data.parent_id,
                                                data.value,
                                                data.label
                                            )
                                        "
                                    >
                                        <el-icon :size="20">
                                            <Edit />
                                        </el-icon>
                                    </el-button>
                                    <el-button
                                        class="w15 pd0 mg0"
                                        text
                                        title="删除当前文件夹(并删除所属下级文件夹)"
                                        @click="treeRemove(node, data)"
                                    >
                                        <el-icon :size="18">
                                            <Delete />
                                        </el-icon>
                                    </el-button>
                                </span>
                            </span>
                        </template>
                    </el-tree>
                </div>
            </div>
            <div :style="{ width: pcWidth }">
                <div class="h30 lh30">
                    <el-row :gutter="20" class="border_line_ddd">
                        <el-col :span="16" class="">
                            <el-breadcrumb separator="/">
                                <el-breadcrumb-item class="lh30">
                                    <el-button
                                        size="small"
                                        class="w26 cursor"
                                        text
                                        title="显示所有文件"
                                        @click="btnViewAllFile"
                                        style="margin-top: -3px"
                                    >
                                        <el-icon :size="22">
                                            <Folder />
                                        </el-icon>
                                    </el-button>
                                    文件路径：
                                    <label v-if="breadTreeList.length == 0"
                                        >/</label
                                    >
                                </el-breadcrumb-item>
                                <el-breadcrumb-item
                                    v-for="(item, index) in breadTreeList"
                                    :key="index"
                                    class="line-clamp lh30"
                                >
                                    {{ item }}
                                </el-breadcrumb-item>
                            </el-breadcrumb>
                        </el-col>
                        <el-col :span="8" class="textR">
                            <el-button
                                size="small"
                                class="w26 mgR10"
                                text
                                title="上传文件"
                                @click="btnUploadFile"
                            >
                                <el-icon :size="26">
                                    <UploadFilled />
                                </el-icon>
                            </el-button>
                            <el-button
                                size="small"
                                class="w26"
                                text
                                title="批量删除文件"
                                @click="btnDelFile"
                                v-if="total"
                            >
                                <el-icon :size="22">
                                    <Delete />
                                </el-icon>
                            </el-button>
                        </el-col>
                    </el-row>
                </div>
                <div
                    class="overflow-y mgT20 mgB5"
                    :style="{ height: pcHeight3 }"
                >
                    <div v-if="total > 0">
                        <el-checkbox-group v-model="multipleSelection">
                            <el-card
                                shadow="hover"
                                class="inline-block w200 h165 mgR15 mgB10"
                                v-for="(item, index) in tableData"
                                :key="item"
                            >
                                <template #header>
                                    <el-row :gutter="10" class="h30">
                                        <el-col :span="6" class="mgL5">
                                            <el-checkbox :value="item.id"
                                                >{{}}
                                            </el-checkbox>
                                        </el-col>
                                        <el-col :span="17" class="textR lh30">
                                            <el-button
                                                size="small"
                                                class="pd0"
                                                text
                                                title="修改分类"
                                                @click="removeFile(item)"
                                            >
                                                <el-icon
                                                    :size="18"
                                                    color="#999"
                                                >
                                                    <Edit />
                                                </el-icon>
                                            </el-button>
                                        </el-col>
                                    </el-row>
                                </template>
                                <div style="">
                                    <el-image
                                        :src="require('@/assets/logo.png')"
                                        loading="lazy"
                                        fit="fill"
                                        style="width: 100px; height: 100px"
                                        class="cursor mgL45"
                                        @click="openFile(item)"
                                        v-if="
                                            item.file_suffix != 'jpg' &&
                                            item.file_suffix != 'png' &&
                                            item.file_suffix != 'gif'
                                        "
                                    />
                                    <el-image
                                        :src="item.file_path"
                                        loading="lazy"
                                        fit="fill"
                                        style="width: 100%; height: 100px"
                                        class="cursor"
                                        preview-teleported
                                        :preview-src-list="previewSrcList"
                                        :initial-index="index"
                                        v-else
                                    />
                                </div>
                                <div
                                    class="textC h30 line-clamp"
                                    :title="item.file_old_name"
                                >
                                    {{ item.file_old_name }}
                                </div>
                            </el-card>
                        </el-checkbox-group>
                    </div>
                    <div class="mgT30 textC" v-else>
                        <span class="color9">{{ loadingDataMsg2 }}</span>
                    </div>
                </div>

                <div class="bgColorF h30 mgT10" v-if="total > 0">
                    <el-pagination
                        background
                        size="small"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[10, 30, 50, 70, 100]"
                        :page-size="pageNum"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                    >
                    </el-pagination>
                </div>
            </div>
        </div>
        <el-drawer
            :close-on-press-escape="false"
            :close-on-click-modal="false"
            v-model="uploadDrawerFlag"
            :title="drawerTitle"
            size="70%"
        >
            <uploads
                @btnUploadDrawer="checkUploadDrawerFlag"
                @btnUpdateList="checkUpdateList"
                :fileTypeID="fileTypeID"
                :folder_name="tmpFolderName"
                :extractTreeData="extractTreeData"
            ></uploads>
        </el-drawer>
        <el-dialog
            v-model="editDialogVisible"
            title="修改文件所属分类"
            width="400"
            draggable
            :close-on-press-escape="false"
            :close-on-click-modal="false"
        >
            <div>
                <el-cascader
                    clearable
                    v-model="editTypeIdNew"
                    :options="folderData"
                    @change="editFileHandleChange"
                    style="width: 95%"
                    :props="{ checkStrictly: true }"
                    placeholder="请选择新的分类"
                />
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="btnEditFileType(1)">取消</el-button>
                    <el-button type="primary" @click="btnEditFileType(2)">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {
    ref,
    reactive,
    onMounted,
    onUnmounted,
    watch,
    getCurrentInstance,
} from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { getLocal } from "@/store/funcs";

import uploads from "@/views/user/fileUpload.vue";

import user from "@/store/api/user";

const { proxy } = getCurrentInstance() as any;
const userInfo: any = ref({});
const pcHeight = ref(document.body.clientHeight - 70 + "px");
const pcHeight2 = ref(document.body.clientHeight - 130 + "px");
const pcHeight3 = ref(document.body.clientHeight - 180 + "px");
const pcWidth = ref(document.body.clientWidth - 650 + "px");

const treeRef: any = ref<FormInstance>() as any;
const filterText = ref("");
const folderData = ref([]);
const defaultProps = ref({
    children: "children",
    label: "label",
});
const loadingDataMsg = ref("数据加载中...");
const treeHighlightCurrent = ref(true);
const fileTypeID = ref("");
const treeFileTypeIDs: any = ref([]);
const tmpFolderName = ref("");
const breadTreeList: any = ref([]);
const extractTreeData: any = ref([]);

const drawerTitle = ref("上传文件");
const uploadDrawerFlag = ref(false);

const total = ref(0);
const currentPage = ref(1); //当前第几页
const pageNum = ref(process.env.pageNum || 30); //每页条数
type tmpTableDataField = {
    id: string;
    file_path: string;
    file_path_compress: string;
    file_suffix: string;
    file_old_name: string;
    file_name: string;
};
const tableData = ref<tmpTableDataField[]>([]);
const multipleSelection = ref([]);
const previewSrcList: any = ref([]);
const loadingDataMsg2 = ref("数据加载中...");

const editDialogVisible = ref(false);
const editTypeId = ref("");
const editTypeIdNew = ref([]);
const editFileID = ref(0);

watch([filterText], ([filterTextNew], [filterTextOld]) => {
    if (filterTextNew !== filterTextOld) {
        treeRef.value.filter(filterTextNew);
    }
});

onMounted(() => {
    const myLocalData = getLocal("myLocalData");
    if (myLocalData && myLocalData.account) {
        userInfo.value = myLocalData;
        getFolderList();
    } else {
        proxy.$funcs.openPage("/login");
    }
});

const getFolderList = async () => {
    loadingDataMsg.value = "数据加载中...";
    const obj = {
        account: userInfo.value.account,
        type: "1",
        op: "1",
    };
    const tmpResult: any = await user.apiUserFile(obj);
    console.log("getFolderList tmpResult", tmpResult);
    if (tmpResult.code === 1) {
        folderData.value = tmpResult.data.count > 0 ? tmpResult.data.list : [];
        loadingDataMsg.value = tmpResult.data.count > 0 ? "" : "没有数据";
        getFileList();
    } else {
        ElMessage({
            type: "error",
            message: tmpResult.msg,
        });
        return false;
    }
};

const folderSubmit = (opType: any, parentId: any, tmpId: any, label: any) => {
    ElMessageBox.prompt(
        tmpId
            ? "请输入要修改的文件夹名称（" + label + "）"
            : "请输入新增文件夹的名称",
        "提示",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            inputPlaceholder: "输入文件夹名称",
            draggable: true,
            inputPattern: /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]{1,40}$/,
            inputErrorMessage:
                "文件夹命名错误（包含中文、数字、字母,不能以_开头和结尾,1-40个字符）",
        }
    )
        .then(async ({ value }) => {
            const obj = {
                account: userInfo.value.account,
                type: "1",
                op: opType,
                formData: JSON.stringify({
                    folder_name: value,
                    parent_id: parentId ? parentId : "",
                    id: tmpId,
                }),
            };
            const tmpResult: any = await user.apiUserFile(obj);
            ElMessage({
                type: tmpResult.code == 1 ? "success" : "error",
                message: tmpResult.msg,
            });
            if (tmpResult.code === 1) {
                getFolderList();
            }
        })
        .catch(() => {});
};

const treeRemove = (node: any, data: any) => {
    ElMessageBox.confirm(
        "确定要删除当前 " +
            data.label +
            " 文件夹吗?（同时删除此文件夹下的所属文件夹）",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }
    )
        .then(async () => {
            const obj = {
                account: userInfo.value.account,
                type: "1",
                op: "4",
                formData: JSON.stringify(data.value),
            };
            const tmpResult: any = await user.apiUserFile(obj);
            ElMessage({
                type: tmpResult.code == 1 ? "success" : "error",
                message: tmpResult.msg,
            });
            if (tmpResult.code === 1) {
                total.value = 0;
                tableData.value = [];
                currentPage.value = 1;
                fileTypeID.value = "";
                tmpFolderName.value = "";
                treeFileTypeIDs.value = [];
                getFolderList();
            }
        })
        .catch(() => {});
};

const filterNode = (value: any, data: any) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
};

//获取当前树节点和其父级节点
const getTreeNode = (node: any) => {
    if (node && node.label !== undefined) {
        breadTreeList.value.unshift(node.label); //在数组头部添加元素
        if (node["data"]["value"]) {
            extractTreeData.value.unshift(node["data"]["value"]);
        }
        getTreeNode(node.parent); //递归
    }
};

const getTreeChildrenIds = (groups: any, groupsIdName: any) => {
    //递归查询树当前节点及包含节点内容
    const { children } = groups;
    if (!Array.isArray(children) || !children.length) return false;
    children.forEach((item: any) => {
        const { value, label } = item;
        if (groupsIdName.indexOf({ value, label }) === -1) {
            groupsIdName.push({ value, label });
        }
        getTreeChildrenIds(item, groupsIdName);
    });

    return groupsIdName;
};

const btnCheckNode = (node: any, ev: any) => {
    fileTypeID.value = "";
    treeFileTypeIDs.value = [];
    tmpFolderName.value = "";
    breadTreeList.value = []; //初始化
    if (ev) {
        getTreeNode(ev);
        fileTypeID.value = node.value;
        tmpFolderName.value = node.label;
        treeFileTypeIDs.value.push(node.value);

        if (node.children.length) {
            const tmpTypeIDs = getTreeChildrenIds(
                {
                    children: node.children,
                },
                []
            );

            if (Object.keys(tmpTypeIDs).length > 0) {
                tmpTypeIDs.forEach((item: any) => {
                    if (item.value) {
                        treeFileTypeIDs.value.push(item.value);
                    }
                });
            }
        }

        if (breadTreeList) {
            var tmpTitle = "";
            breadTreeList.value.forEach((item: any) => {
                tmpTitle += " / " + item;
            });
            drawerTitle.value = "上传文件：（路径：" + tmpTitle + "）";
        }
        console.log("treeFileTypeIDs", treeFileTypeIDs.value);

        treeHighlightCurrent.value = true;
        total.value = 0;
        tableData.value = [];
        previewSrcList.value = [];
        currentPage.value = 1;
        loadingDataMsg2.value = "数据载入中...";
        getFileList();
    }
};

const handleDragEnd = async (
    draggingNode: any,
    dropNode: any,
    dropType: any,
    ev: any
) => {
    if (draggingNode["data"]) {
        // const obj = {
        //     account: userInfo.value.account,
        //     type: "1",
        //     op: "6",
        //     formData: JSON.stringify(draggingNode["data"]),
        //     formData2: JSON.stringify(dropNode["data"]),
        //     dropType: dropType,
        // };
        // const tmpResult: any = await user.apiUserFile(obj);
        // ElMessage({
        //     type: tmpResult.code == 1 ? "success" : "error",
        //     message: tmpResult.msg,
        // });
    } else {
        ElMessage({
            type: "info",
            message: "请先选择内容",
        });
        return false;
    }
};

const btnViewAllFile = () => {
    breadTreeList.value = [];
    extractTreeData.value = [];
    treeHighlightCurrent.value = false;
    fileTypeID.value = "";
    treeFileTypeIDs.value = [];
    tmpFolderName.value = "";
    total.value = 0;
    tableData.value = [];
    previewSrcList.value = [];
    currentPage.value = 1;
    loadingDataMsg2.value = "数据载入中...";
    getFileList();
};

const getFileList = async () => {
    const obj = {
        account: userInfo.value.account,
        type: 2,
        op: 1,
        type_id: treeFileTypeIDs.value,
        page: currentPage.value,
        pageNum: pageNum.value,
    };
    const tmpResult: any = await user.apiUserFile(obj);
    if (tmpResult.code === 1) {
        total.value = tmpResult.data.count;
        tableData.value = tmpResult.data.count ? tmpResult.data.list : [];
        tableData.value.forEach((item: any) => {
            if (item.file_path) {
                previewSrcList.value.push(item.file_path);
            }
        });
    } else {
        ElMessage({
            type: "error",
            message: tmpResult.msg,
        });
        return false;
    }
    loadingDataMsg2.value = total.value > 0 ? "" : "没有数据";
};

const btnDelFile = () => {
    if (multipleSelection.value.length == 0) {
        return ElMessage({
            type: "info",
            message: "请选择要删除的数据",
        });
    }
    ElMessageBox.confirm("确定要删除所选数据吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            const delArr: any = [];
            multipleSelection.value.forEach((item, index) => {
                delArr[index] = item;
            });
            const obj = {
                account: userInfo.value.account,
                type: 2,
                op: 4,
                formData: JSON.stringify(delArr),
            };
            console.log("delfile obj", obj);

            const tmpResult: any = await user.apiUserFile(obj);
            ElMessage({
                type: tmpResult.code == 1 ? "success" : "error",
                message: tmpResult.msg,
            });
            if (tmpResult.code === 1) {
                getFileList();
            }
        })
        .catch(() => {});
};

const handleSizeChange = (val: any) => {
    total.value = 0;
    tableData.value = [];
    currentPage.value = 1;
    previewSrcList.value = [];
    pageNum.value = val;
    loadingDataMsg2.value = "数据载入中...";
    getFileList();
};
const handleCurrentChange = (val: any) => {
    total.value = 0;
    tableData.value = [];
    previewSrcList.value = [];
    currentPage.value = val;
    loadingDataMsg2.value = "数据载入中...";
    getFileList();
};

const removeFile = (row: any) => {
    if (row) {
        editDialogVisible.value = true;
        editFileID.value = row.id;
        editTypeId.value = editTypeIdNew.value = row.folder_id;
    }
};

const openFile = (item: any) => {
    if (item.file_path) {
        window.open(item.file_path, "_blank");
    }
};

const btnUploadFile = () => {
    uploadDrawerFlag.value = true;
};

const checkUploadDrawerFlag = () => {
    uploadDrawerFlag.value = false;
};

const checkUpdateList = () => {
    total.value = 0;
    tableData.value = [];
    previewSrcList.value = [];
    loadingDataMsg2.value = "数据载入中...";
    getFileList();
};

const btnEditFileType = (flag: any) => {
    if (flag == 1) {
        //取消
        editDialogVisible.value = false;
        editTypeId.value = "";
        editTypeIdNew.value = [];
    } else if (flag == 2) {
        if (!editTypeIdNew.value) {
            ElMessage({
                type: "error",
                message: "请选择分类",
            });
            return false;
        }
        if (
            editTypeIdNew.value[editTypeIdNew.value.length - 1] ==
                editTypeId.value ||
            editTypeIdNew.value.toString() == editTypeId.value.toString()
        ) {
            ElMessage({
                type: "error",
                message: "请选择不同的分类",
            });
            return false;
        }

        ElMessageBox.confirm("确定要修改文件分类吗", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(async () => {
                const obj = {
                    account: userInfo.value.account,
                    type: 2,
                    op: 3,
                    formData: JSON.stringify({
                        value: editFileID.value,
                        editTypeId: editTypeId.value,
                        new_type_id:
                            editTypeIdNew.value[editTypeIdNew.value.length - 1],
                    }),
                };
                console.log("file obj", obj);

                const tmpResult: any = await user.apiUserFile(obj);
                ElMessage({
                    type: tmpResult.code == 1 ? "success" : "error",
                    message: tmpResult.msg,
                });
                if (tmpResult.code === 1) {
                    editDialogVisible.value = false;
                    editTypeId.value = "";
                    editTypeIdNew.value = [];
                    getFileList();
                }
            })
            .catch(() => {});
    }
};

const editFileHandleChange = (value: any) => {};

onUnmounted(() => {});
</script>

<style lang="less" scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>
